package com.motong.gongdan.util;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCursor;
import com.motong.gongdan.entity.CustomField;
import com.motong.gongdan.service.CustomFieldService;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:fff
 * @time:2022/7/13
 */
public class MongoUtils {

    public static List<Object> getSearchResult(Map<Integer, String> customMap, String type, CustomFieldService customFieldService, MongoTemplate mongoTemplate) {
        List<Document> aggregateList = new ArrayList<>();
        Document sub_match = new Document();
        Document match = new Document("$match", sub_match);
        customMap.keySet().forEach(k -> {
            CustomField cf = customFieldService.getById(k);
            sub_match.append("customFieldMess.customFieldId", k);
            String v = customMap.get(k);
            if ("inputNumber".equals(cf.getFieldType()) || "datePicker".equals(cf.getFieldType())) {
                if (!v.contains(",")) {
                    sub_match.append("customFieldMess.value", new Document("$gte", String.join(": ", "-1", ",", "$lte", ": ", "0")));
                } else {
                    List<String> value = Arrays.stream(v.split(",")).filter(StringUtils::hasLength).collect(Collectors.toList());
                    if (value.size() == 1) {
                        if (v.startsWith(",")) {
                            sub_match.append("customFieldMess.value", new Document("$lte", value.get(0)));
                        } else {
                            sub_match.append("customFieldMess.value", new Document("$gte", value.get(0)));
                        }
                    } else {
                        sub_match.append("customFieldMess.value", new Document("$gte", String.join(": ", value.get(0), ",", "$lte", ": ", value.get(1))));
                    }
                }
            } else if ("selectChecked".equals(cf.getFieldType())) {
                String newValue = Arrays.stream(v.split(",")).map(i -> "\"".concat(i).concat("\"")).collect(Collectors.joining("|"));
                sub_match.append("customFieldMess.value", new Document("$regex", newValue));
            } else {
                sub_match.append("customFieldMess.value", new Document("$regex", String.join(": ", customMap.get(k))));
            }
        });
        aggregateList.add(match);
        AggregateIterable aggregateIterable = mongoTemplate.getCollection(type).aggregate(aggregateList).allowDiskUse(true);
        MongoCursor cursor = aggregateIterable.iterator();
        List<Object> list = new ArrayList<>();
        while (cursor.hasNext()) {
            Object object = cursor.next();
            //System.out.println(JSON.toJSONString(object));
            list.add(object);
        }
        return CollectionUtils.isEmpty(list) ? Collections.emptyList() : list;
    }

    public static void deleteById(Integer id, MongoTemplate mongoTemplate, String collection) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        mongoTemplate.remove(query, collection);
    }
}
